<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <h1>增加数据 </h1>
  姓名：<input type="text" class="user"> <br>
  性别：<input type="text" class="gender"><br>
  地址：<input type="text" class="address"><br>
  <button class="btn">提交</button>
  <hr>
  <h1>列表渲染</h1>
  <ul class="content">
    <% data.forEach((item, index) => { %>
    <li class="listdom">
      <span><%= item.user%></span>
      <span><%= item.gender%></span>
      <span><%= item.address%></span>
      <button data-index=<%= index%> class="deleteBtn">删除</button>
    </li>
    <%})%>
  </ul>

  <script src="js/axios.js"></script>

  <script>
    const btn = document.querySelector('.btn')
    const content = document.querySelector('.content')
    const user = document.querySelector('.user')
    const gender = document.querySelector('.gender')
    const address = document.querySelector('.address')
    const deleteBtn = document.querySelectorAll('.deleteBtn')
    btn.onclick = function () {
      if (user.value && gender.value && address.value) {
        axios.post('/api/add', {
          user: user.value.trim(),
          gender: gender.value.trim(),
          address: address.value.trim(),
        }).then(res => {
          const data = res.data.data
          content.innerHTML = data.map(((item, index) => {
            return `<li>
              <span>${item.user}</span>
              <span>${item.gender}</span>
              <span>${ item.address}</span>
              <button data-index=${index} class="deleteBtn">删除</button>
            </li>`
          })).join('')
        })
      } else {
        alert('内容不能为空')
      }
    }


    // 针对后添加的元素要添加事件，必须使用事件委托
    content.onclick = function (e) {
      let target = e.target;
      console.log(target, 'gender')
      let index = target.dataset.index;
      console.log(index, 'index')
      if (target.nodeName === 'BUTTON') {
        axios.get('/api/delete', {
          params: {
            index: index
          }
        }).then(res => {
          const data = res.data.data;
          content.innerHTML = data.map(((item, index) => {
            return `<li>
              <span>${item.user}</span>
              <span>${item.gender}</span>
              <span>${ item.address}</span>
              <button data-index=${index} class="deleteBtn">删除</button>
            </li>`
          })).join('')
        })
      }
    }

    // deleteBtn.forEach(item => {
    //   item.onclick = function () {
    //     axios.get('/api/delete', {
    //       params: {
    //         id: item.id
    //       }
    //     }).then(res => {
    //       console.log(res)
    //     })
    //   }
    // })


    // function getData() {
    //   axios.get('/api/list').then(res => {

    //   })
    // }

  </script>
</body>

</html>